package include.nseer_cookie;

import java.io.*;
import java.util.jar.*;

public class ZipUtil {

    protected static byte buf[] = new byte[1024];

    private static void recurseFiles(JarOutputStream jos, File file, String pathName)
            throws IOException, FileNotFoundException {
        if (file.isDirectory()) {
            pathName = pathName + file.getName() + "/";
            jos.putNextEntry(new JarEntry(pathName));
            String fileNames[] = file.list();
            if (fileNames != null) {
                for (int i = 0; i < fileNames.length; i++) {
                    recurseFiles(jos, new File(file, fileNames[i]), pathName);
                }
            }
        } else {
            JarEntry jarEntry = new JarEntry(pathName + file.getName());
            FileInputStream fin = new FileInputStream(file);
            BufferedInputStream in = new BufferedInputStream(fin);
            jos.putNextEntry(jarEntry);
            int len;
            while ((len = in.read(buf)) >= 0) {
                jos.write(buf, 0, len);
            }
            in.close();
            jos.closeEntry();
        }
    }

    public static void makeDirectoryToZip(File directory, File zipFile, String zipFolderName, int level)
            throws IOException, FileNotFoundException {
        level = checkZipLevel(level);
        if (zipFolderName == null) {
            zipFolderName = "";
        }
        JarOutputStream jos = new JarOutputStream(new FileOutputStream(zipFile), new Manifest());
        jos.setLevel(level);
        String fileNames[] = directory.list();
        if (fileNames != null) {
            for (int i = 0; i < fileNames.length; i++) {
                recurseFiles(jos, new File(directory, fileNames[i]), zipFolderName);
            }
        }
        jos.close();
    }

    public static int checkZipLevel(int level) {
        if (level < 0 || level > 9) {
            level = 7;
        }
        return level;
    }
}